package com.qzsoft.zhjd.server.modules.ludong.exp.service.impl;

import com.qzsoft.zhjd.server.common.utils.CommonConstants;
import com.qzsoft.zhjd.server.modules.ludong.exp.constants.PlatformEnums;
import com.qzsoft.zhjd.server.modules.ludong.exp.dto.AsphaltRequiresAndRefDto;
import com.qzsoft.zhjd.server.modules.ludong.exp.entity.*;
import com.qzsoft.zhjd.server.modules.ludong.exp.mapper.CollectExpDuctilityMapper;
import com.qzsoft.zhjd.server.modules.ludong.exp.service.CollectAsphaltRequiresRefService;
import com.qzsoft.zhjd.server.modules.ludong.exp.service.CollectExpDuctilityService;
import com.qzsoft.zhjd.server.modules.ludong.exp.service.CollectLaboratoryDeviceService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.zhjd.server.modules.ludong.exp.mapper.CollectLaboratoryPenetrationMapper;
import com.qzsoft.zhjd.server.modules.ludong.exp.mapper.CollectLaboratorySofteningPointMapper;
import com.qzsoft.zhjd.server.modules.ludong.exp.mapper.CollectMarshallStabilityMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;


@Service("expDuctilityService")
public class CollectExpDuctilityServiceImpl extends ServiceImpl<CollectExpDuctilityMapper, CollectExpDuctilityEntity> implements CollectExpDuctilityService {

    @Autowired
    private CollectAsphaltRequiresRefService requiresRefService;
    @Autowired
    private CollectLaboratoryDeviceService deviceService;
    @Autowired
    private CollectLaboratorySofteningPointMapper softeningPointMapper;
//    @Autowired
//    private LaboratoryDuctilityMapper ductilityMapper;
    @Autowired
    private CollectLaboratoryPenetrationMapper penetrationMapper;
    @Autowired
    private CollectMarshallStabilityMapper stabilityMapper;

    /**
     * 功能描述: 先删除后添加
     * @param collectExpDuctilityEntity 实体类
     * @return : void
     * @author : liugf
     * @date : 2020/6/10 20:39
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertAndRemoveData(CollectExpDuctilityEntity collectExpDuctilityEntity) {
        removeById(collectExpDuctilityEntity.getId());
        save(collectExpDuctilityEntity);
    }

    @Override
    @Transactional
    public void saveAsphalt(CollectPlatformLaboratoryDataEntity entity) {
        QueryWrapper<AsphaltRequiresAndRefDto> query = new QueryWrapper<>();
        query.eq("ar.name",entity.getSampleName()).eq(StringUtils.isNotBlank(entity.getTestTemp()),"arr.temperature",entity.getTestTemp())
                .eq("arr.type",entity.getTestType());
        query.orderByAsc("arr.temperature");
        query.last("LIMIT 1");
        AsphaltRequiresAndRefDto asreq = requiresRefService.getRequiresByAspIdAndType(query);
        CollectLaboratoryDeviceEntity device = getDeviceDeptId(entity.getEquipmentNumber());
        entity.setDeviceId(device.getId());
        entity.setDeptId(device.getBaseCode());
        entity.setDeptPkid(device.getDeptPkid());
        if(ObjectUtils.isEmpty(asreq)){//直接入库
            addPlatformLaboratoryData(entity,CommonConstants.NO_DELETED);
        }else {
            String is_qualified = checkRequires(entity,asreq);
            entity.setIsQualified(is_qualified);
            entity.setMaxValue(asreq.getMaxValue());
            entity.setMinValue(asreq.getMinValue());
            if(StringUtils.isNotBlank(entity.getTestTemp())){
                entity.setTempature(new BigDecimal(entity.getTestTemp()));
            }
            addPlatformLaboratoryData(entity,entity.getIsQualified());
        }
    }

    public String checkRequires(CollectPlatformLaboratoryDataEntity entity, AsphaltRequiresAndRefDto reqires){
        try{
            String value = String.valueOf(entity.getAverage());
            if(new BigDecimal(value).compareTo(reqires.getMinValue()) >=0){
                if(ObjectUtils.isNotNull(reqires.getMaxValue()) && new BigDecimal(value).compareTo(reqires.getMaxValue())<=0){
                    return "0";
                }
                return "0";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "1";
    }
    public void addPlatformLaboratoryData(CollectPlatformLaboratoryDataEntity entity, String is_qualified){
        switch (entity.getTestType()){
            case CommonConstants.RHD : {
                QueryWrapper<CollectLaboratorySofteningPointEntity> query = new QueryWrapper<>();
                query.eq("sample_no",entity.getSampleNo());
                CollectLaboratorySofteningPointEntity sentity = softeningPointMapper.selectOne(query);
                if(ObjectUtils.isEmpty(sentity)){
                    CollectLaboratorySofteningPointEntity spe = new CollectLaboratorySofteningPointEntity();
                    BeanUtils.copyProperties(entity,spe);
                    spe.setIsQualified(is_qualified);
                    spe.setValue1(new BigDecimal(entity.getSoftenP()));
                    softeningPointMapper.insert(spe);
                }else{
                    sentity.setId(sentity.getId());
                    sentity.setIsQualified(is_qualified);
                    sentity.setValue1(new BigDecimal(entity.getSoftenP()));
                    sentity = (CollectLaboratorySofteningPointEntity)setValue(sentity,entity);
                    softeningPointMapper.updateById(sentity);
                }
            };break;
            case CommonConstants.YD : {
//                QueryWrapper<LaboratoryDuctilityEntity> query = new QueryWrapper<>();
//                query.eq("sample_no",entity.getSampleNo());
//                LaboratoryDuctilityEntity dentity = ductilityMapper.selectOne(query);
//                if(ObjectUtils.isEmpty(dentity)){
//                    LaboratoryDuctilityEntity spe = new LaboratoryDuctilityEntity();
//                    BeanUtils.copyProperties(entity,spe);
//                    spe.setIsQualified(is_qualified);
//                    spe.setAverage(entity.getAverageDuctility());
//                    spe.setValue1(new BigDecimal(entity.getDuctility()));
//                    ductilityMapper.insert(spe);
//                }else{
//                    dentity.setId(dentity.getId());
//                    dentity.setAverage(entity.getAverageDuctility());
//                    dentity.setIsQualified(is_qualified);
//                    dentity = (LaboratoryDuctilityEntity)setValue(dentity,entity);
//                    ductilityMapper.updateById(dentity);
//                }
            };break;
            case CommonConstants.ZRD : {
                QueryWrapper<CollectLaboratoryPenetrationEntity> query = new QueryWrapper<>();
                query.eq("sample_no",entity.getSampleNo());
                CollectLaboratoryPenetrationEntity pentity = penetrationMapper.selectOne(query);
                if(ObjectUtils.isEmpty(pentity)) {
                    CollectLaboratoryPenetrationEntity spe = new CollectLaboratoryPenetrationEntity();
                    BeanUtils.copyProperties(entity,spe);
                    spe.setIsQualified(is_qualified);
                    spe.setValue1(new BigDecimal(entity.getPenetration()));
                    penetrationMapper.insert(spe);
                }else{
                    pentity.setId(pentity.getId());
                    pentity.setIsQualified(is_qualified);
                    pentity = (CollectLaboratoryPenetrationEntity)setValue(pentity,entity);
                    penetrationMapper.updateById(pentity);
                }
            };break;
            case CommonConstants.MARSHALL : {
                QueryWrapper<CollectMarshallStabilityEntity> query = new QueryWrapper<>();
                query.eq("sample_no",entity.getSampleNo());
                CollectMarshallStabilityEntity pentity = stabilityMapper.selectOne(query);
                if(ObjectUtils.isEmpty(pentity)) {
                    CollectMarshallStabilityEntity spe = new CollectMarshallStabilityEntity();
                    BeanUtils.copyProperties(entity,spe);
                    spe.setStabilityValue(entity.getStabilityValue());
                    spe.setIsQualified(is_qualified);
                    spe.setFlow1(new BigDecimal(entity.getFlow()));
                    spe.setStability1(new BigDecimal(entity.getStability()));
                    stabilityMapper.insert(spe);
                }else{
                    pentity.setId(pentity.getId());
                    pentity.setIsQualified(is_qualified);
                    pentity = (CollectMarshallStabilityEntity)setMarshallValue(pentity,entity);
                    stabilityMapper.updateById(pentity);
                }
            };break;
        }
    }
    public Object setMarshallValue(Object t, CollectPlatformLaboratoryDataEntity entity){
        try{
            Field ff = null;
            Field flow = null;
            if(StringUtils.equals(entity.getTestFr(), PlatformEnums.MARSHALL1.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL1.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW1.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL2.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL2.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW2.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL3.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL3.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW3.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL4.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL4.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW4.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL5.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL5.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW5.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.MARSHALL6.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.MARSHALL6.getColumn());
                flow = t.getClass().getDeclaredField(PlatformEnums.FLOW6.getColumn());
            }
            ff.setAccessible(true);
            flow.setAccessible(true);
            ReflectionUtils.setField(ff,t,new BigDecimal(entity.getStability()));
            ReflectionUtils.setField(flow,t,new BigDecimal(entity.getFlow()));
        }catch (Exception e){
            e.printStackTrace();
        }
        return t;
    }

    public Object setValue(Object t, CollectPlatformLaboratoryDataEntity entity){
        try{
            Field ff = null;
            if(StringUtils.equals(entity.getTestFr(), PlatformEnums.VALUE1.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.VALUE1.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.VALUE2.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.VALUE2.getColumn());
            }
            if(StringUtils.equals(entity.getTestFr(),PlatformEnums.VALUE3.getCode())){
                ff = t.getClass().getDeclaredField(PlatformEnums.VALUE3.getColumn());
            }
            ff.setAccessible(true);
            if(StringUtils.equals(entity.getTestType(),CommonConstants.RHD)){
                ReflectionUtils.setField(ff,t,new BigDecimal(entity.getSoftenP()));
            }if(StringUtils.equals(entity.getTestType(),CommonConstants.YD)){
                ReflectionUtils.setField(ff,t,new BigDecimal(entity.getDuctility()));
            }if(StringUtils.equals(entity.getTestType(),CommonConstants.ZRD)){
                ReflectionUtils.setField(ff,t,new BigDecimal(entity.getPenetration()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return t;
    }


    public CollectLaboratoryDeviceEntity getDeviceDeptId(String equipmentNumber){
        QueryWrapper<CollectLaboratoryDeviceEntity> query = new QueryWrapper();
        query.eq("deleted", CommonConstants.NO_DELETED)
                .eq("unique_code",equipmentNumber);
        CollectLaboratoryDeviceEntity entity = deviceService.getOne(query);
        Assert.notNull(entity,"设备不存在！");
        return entity;
    }
}
